import { ref, onMounted, type Ref } from 'vue'
type ReturnObjType<T> = {
  target: Ref<HTMLElement>
  dataList: Ref<T>
}
// 定义数据懒加载函数
export const useLazyData = <T>(getDataFn: any): ReturnObjType<T> => {
  // 渲染数组
  const dataList = ref<T>() as Ref<T>
  // 接收dom元素容器
  const target = ref<HTMLElement>() as Ref<HTMLElement>
  // 定义检测可视元素函数
  const observer = new IntersectionObserver(async (entries) => {
    const [viewport] = entries
    if (viewport.intersectionRatio) {
      const res = await getDataFn()
      dataList.value = res.result
      // 请求完成取消监听
      observer.unobserve(target.value!)
    }
  })
  onMounted(() => {
    // 开始监听每个元素
    observer.observe(target.value!)
  })
  return { target, dataList }
}
